/*
 * @Author: jianglijun 
 * @Date: 2019-04-20 21:30:24 
 * @Last Modified by: jianglijun
 * @Last Modified time: 2019-04-24 23:45:03
 */
const Koa = require('koa')
const app = new Koa()
// const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const router = require("koa-router")()
const session = require('koa-session');
const render = require('koa-art-template')
const defaultRouter = require('./routes/default/index.js');
const apiRouter = require('./routes/api.js');
const {store,renderConfig} = require("./utils/comm.js")
require('koa-onerror')(app)
// app.use(bodyparser({
//   enableTypes:['json', 'form', 'text']
// }))
app.use(require("./middleware/formidable")());
app.use(require('koa-json')())
app.use(logger())
app.keys = ['jianglijun juna'];
app.use(session({store},app));
render(app,renderConfig);
// logger
app.use(require("./middleware/rewrite.js")());
app.use(async (ctx,next) => {
  if(ctx.session.user){
    await next();
  }else{
    if(ctx.originalUrl.startsWith("/api/getPic") || ctx.originalUrl.startsWith("/public/") || ctx.originalUrl == '/user/login' || ctx.originalUrl == '/user/islogin' || ctx.originalUrl == "/user/register" || ctx.originalUrl == '/user/lout' || ctx.originalUrl == '/user/registerlogin' || ctx.originalUrl == '/user/registerUser' || ctx.originalUrl == '/user/userlogin' || ctx.originalUrl == '/user/check-username')
    {
      await next();
    }else{
      ctx.redirect("/user/login");
    }
  }
})
app.use(require("./middleware/error")());
app.use(require('koa-static')(__dirname + '/public'))
app.use(async (ctx,next) => {
   ctx.state.user = ctx.session.user;
   await next();
})
// routes
router.use(defaultRouter.routes());
router.use(apiRouter.routes());
app
  .use(router.routes())
  .use(router.allowedMethods());
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});
module.exports = app
